﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Dynamic;
using System.Text;
using System.Text.RegularExpressions;
using QLHD.Models;
using System.Security.Cryptography;
namespace QLHD.Utilities
{
    public class Utilities
    {
        public static DateTime ConvertToDateTime(string strdate)
        {

            string[] formats = {"dd/MM/yyyy","dd/MM/yyyy hh:mm","M/d/yyyy h:mm:ss tt", "M/d/yyyy h:mm tt", 
                   "MM/dd/yyyy hh:mm:ss", "M/d/yyyy h:mm:ss", 
                   "M/d/yyyy hh:mm tt", "M/d/yyyy hh tt", 
                   "M/d/yyyy h:mm", "M/d/yyyy h:mm", 
                   "MM/dd/yyyy hh:mm", "M/dd/yyyy hh:mm"};
            DateTime dt = new DateTime();
            var aa = new CultureInfo("vi-VN");
            if (!DateTime.TryParse(strdate, out dt) && DateTime.TryParseExact(strdate, formats, aa, DateTimeStyles.None, out dt))
            {
                dt = Convert.ToDateTime(strdate, aa);
            }
            return dt;

        }

        public static string StripDiacritics(string accented)
        {
            Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
            string strFormD = accented.Normalize(System.Text.NormalizationForm.FormD);
            return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
        }


        public static List<string> GetListValues(object target)
        {
            if (target == null)
                return new List<string>();
            object tempobj = null;
            List<string> lstvalue = new List<string>();
            foreach (var prop in target.GetType().GetProperties())
            {
                if (prop.Name != "EntityKey" && (prop.PropertyType.BaseType.Name == "Object" || prop.PropertyType.BaseType.Name == "ValueType"))
                {
                    tempobj = prop.GetValue(target, null);
                    if (tempobj != null)
                    {
                        if (prop.PropertyType.Name == "DateTime" || prop.PropertyType.FullName.Contains("DateTime"))
                        {
                            lstvalue.Add(((DateTime)tempobj).ToString("dd/MM/yyyy"));
                        }
                        else if (prop.PropertyType.Name != "Boolean")
                        {
                            lstvalue.Add(tempobj.ToString().ToLower());
                            lstvalue.Add(StripDiacritics(tempobj.ToString().ToLower()));//khong dau
                        }
                    }
                }
            }

            return lstvalue;
        }

        public static string GetDecimalValue(decimal? val, bool emptyifnullorzero = false)
        {
            if ((val == null || val == 0) && emptyifnullorzero)
            {
                return "";
            }
            else if ((val == null || val == 0) && !emptyifnullorzero)
            {
                val = 0;
            }
            return val != null ? ((decimal)val).ToString("N", CultureInfo.CreateSpecificCulture("en-US")) : "";
        }

        public static void UpdateSearchContent(object obj, object context, bool dosave = true)
        {
            try
            {
                QLHD2013Entities db = (QLHD2013Entities)context;
                HopDong topct = (HopDong)obj;
                List<string> lstvalue = new List<string>();
                List<string> lstrelatevalue = new List<string>();
                lstvalue.AddRange(GetListValues(topct));
                lstvalue.AddRange(GetListValues(topct.DoiTac));
                lstrelatevalue.AddRange(GetRelationValues(topct));
                foreach (HopDong hd in topct.HopDong1.Where(q => q.TrangThaiHD == 1))
                {
                    lstvalue.AddRange(GetListValues(hd));
                    lstvalue.AddRange(GetListValues(topct.DoiTac));
                    lstrelatevalue.AddRange(GetRelationValues(hd));
                }
                lstvalue.AddRange(lstrelatevalue);

                //QLHD2013Entities db = new QLHD2013Entities();
                var shd = db.SearchContents.Where(q => q.MaHD == topct.MaHD).FirstOrDefault();
                if (shd == null)
                {
                    shd = new SearchContent();
                    shd.MaHD = topct.MaHD;
                    shd.Contents = string.Join(Constants.SPLIT_CHAR, lstvalue);
                    db.AddToSearchContents(shd);
                }
                else
                {
                    shd.Contents = string.Join(Constants.SPLIT_CHAR, lstvalue);
                }
                if (dosave)
                {
                    db.SaveChanges();
                }
            }
            catch { }
        }

        private static List<string> GetRelationValues(HopDong hd)
        {
            List<string> lstvalue = new List<string>();
            foreach (var item in hd.XNKLs)
            {
                lstvalue.AddRange(GetListValues(item));
            }
            foreach (var item in hd.KhoanChiPhis)
            {
                lstvalue.AddRange(GetListValues(item));
            }
            return lstvalue;
        }

        #region Cryptograph
        private static string cryptoKey = "1qazxsw@TuanQuang1083";
        public static string Encrypt(string toEncrypt)
        {
            byte[] keyArray;
            byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(cryptoKey));
            hashmd5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateEncryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        public static string Decrypt(string toEncrypt)
        {
            byte[] keyArray;
            byte[] toEncryptArray = Convert.FromBase64String(toEncrypt);
            byte[] DataToDecrypt = Convert.FromBase64String(toEncrypt);
            System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();

            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(cryptoKey));
            hashmd5.Clear();

            TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
            tdes.Key = keyArray;
            tdes.Mode = CipherMode.ECB;
            tdes.Padding = PaddingMode.PKCS7;

            ICryptoTransform cTransform = tdes.CreateDecryptor();
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            tdes.Clear();
            return UTF8.GetString(resultArray, 0, resultArray.Length);
        }
        #endregion

        public static string DuplicateString(string input, int times)
        {
            if (times <= 0)
                return "";
            StringBuilder sb = new StringBuilder(input.Length * times);
            for (int i = 0; i < times; i++)
            {
                sb.Append(input);
            }

            return sb.ToString();
        }

        public static void GetAllKCPTree(ref List<TreeItem> List, int dId, List<KhoanChiPhi> ListAll, ref int Level)
        {
            Level++;
            List<KhoanChiPhi> lstRole = ListAll.FindAll(delegate(KhoanChiPhi re) { return re.ParentID == dId ? true : false; });
            if (ListAll != null && ListAll.Count > 0)
            {
                TreeItem tr;
                foreach (KhoanChiPhi obj in lstRole)
                {
                    tr = new TreeItem();
                    tr.Id = obj.MaKCP.ToString();
                    tr.Name = DuplicateString("--", Level) + obj.NoiDung;
                    List.Add(tr);
                    GetAllKCPTree(ref List, obj.MaKCP, ListAll, ref Level);
                }
                Level--;
            }
        }
    }

    public class Constants
    {
        public const string SPLIT_CHAR = "§";
    }
}